package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.House;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.service.HouseService;
import com.atguigu.util.FileUtil;
import com.atguigu.util.QiniuUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 翟文海
 * @Date: 2022/10/30/030 14:04
 * @Version: 1.0
 * @Description:
 **/
@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {
    private static final String PAGE_UPLOAD = "house/upload";
    private static final String LIST_HOUSE = "redirect:/house";

    @Reference
    private HouseService houseService;

    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(Model model, @PathVariable("houseId") Long houseId, @PathVariable("type") Integer type) {
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);

        return toPage(PAGE_UPLOAD);
    }

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable("houseId") Long houseId, @PathVariable("type") Integer type, @RequestParam("file") List<MultipartFile> files) throws IOException {
        if (CollectionUtils.isEmpty(files)) {
            return Result.fail();
        }
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String uuid = UUID.randomUUID().toString();
            String prefix = uuid.replace("-", "");
            //唯一的文件名
            String fileName = prefix + suffix;
            String dirPath = FileUtil.getRandomDirPath(2, 3);
            //生成二级目录存储图片
            String filePath = dirPath + fileName;
            //上传头像
            QiniuUtils.upload2Qiniu(file.getBytes(), filePath);
            String url = QiniuUtils.getUrl(filePath);
            HouseImage houseImage = new HouseImage();
            houseImage.setHouseId(houseId);
            houseImage.setImageName(filePath);
            houseImage.setImageUrl(url);
            houseImage.setType(type);
            houseImageService.insert(houseImage);

            if (i == 0) {
                House house = houseService.getById(houseId);
                if (house.getDefaultImageUrl() == null || "".equals(house.getDefaultImageUrl())) {
                    house.setDefaultImageUrl(url);
                    houseService.update(house);
                }
            }
        }
        return Result.ok();
    }

    /**
     * @param model
     * @param houseId
     * @param id      房源图片id
     * @return
     */
    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(Model model, @PathVariable("houseId") Long houseId, @PathVariable("id") Long id) {
        //根据图片id查询表中的图片名字
        HouseImage houseImage = houseImageService.getById(id);
        QiniuUtils.deleteFileFromQiniu(houseImage.getImageName());
        houseImageService.delete(id);
        House house = houseService.getById(houseId);
        if (house.getDefaultImageUrl().equals(houseImage.getImageUrl())) {
            house.setDefaultImageUrl("");
            houseService.update(house);
        }
        return toPage(LIST_HOUSE + "/" + houseId);
    }
}
